package com.cloudtasks;
import com.cloudtasks.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

/**
 * @author Administrator
 *
 */
public class GroceryGroupsDisplayPage2Activity extends Activity {
	
	String UserName = "";
	long UserID;
	String ListName = "";
	long ListID;
	String TypeName = "";
	final Context myContext = this;
	private Cursor DBcursor;
	final static String TYPE_PAGE = "type";
	private Database mDb;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_list_itempage);
        
        try{            
        	// Add Button EDIT
	        Button addItem = (Button)findViewById(R.id.item_edit_button);
	        addItem.setOnClickListener(editItemListener);  
        	
	        // Unwrap parameters from last activity: the User's name
	        // and also his User ID
        	Bundle param = getIntent().getExtras(); 
	        if(param != null){
	        	UserName = param.getString("uname");
		        //MyTools.displayToastMessage(myContext, UserName);
		        UserID = param.getLong("uid");
		        ListName = param.getString("");
		    	ListID = param.getLong("lid");
		    	TypeName = param.getString("tname");
	        }
        	 
	        // initialize the Database for this context
	        mDb = new Database(this);
	        mDb.open();
	        ListView lv = (ListView) findViewById(R.id.items_listview);
	        //lv.setItemsCanFocus(false);
	        DBcursor = mDb.fetchAllItemsInListByType(ListID, TypeName);
	        //DBcursor = mDb.fetchAllItemsInListByType(ListID, "Fruit");
	        SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,  
	        	    R.layout.single_item_checkbox,
	        	    DBcursor,
	        	    new String[] {Database.KEY_CHECKED, Database.KEY_GROC_NAME},
	        	    new int[] { R.id.CheckBox1, R.id.text1}
	        	);
	        cursorAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
	            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
	              int nCheckedIndex = cursor.getColumnIndexOrThrow(Database.KEY_CHECKED);
	              if (columnIndex == nCheckedIndex) {
	                CheckBox cb = (CheckBox) view;
	                boolean bChecked = (cursor.getInt(nCheckedIndex) != 0);
	                cb.setChecked(bChecked);
	                cb.setOnCheckedChangeListener(
	                        new CompoundButton.OnCheckedChangeListener() {
	                         public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
	                         // update your value in the db
	                        	 try{
		                        	 ListView lv = (ListView) findViewById(R.id.items_listview);	                        	 
		                        	 int pos = lv.getPositionForView(buttonView);
		                        	 boolean success = mDb.updateItemCheckedState(lv.getAdapter().getItemId(pos), isChecked);
		                        	 if (success == false)
		         						MyTools.displayToastMessage(myContext,
		         								"Error: could not update");
		         					else
		         						MyTools.displayToastMessage(myContext,
		         								"Successfully " + (isChecked?("Checked"):("Unchecked")));
	                        	 }
	                             catch(Exception e){
	                             	MyTools.displayToastMessage(myContext, e.toString());
	                             }	                       
	                             }});
	                return true;
	              }
	              return false;
	            }
	          });
	        lv.setAdapter(cursorAdapter);
	        startManagingCursor(DBcursor);
        }
        catch(Exception e){
        	MyTools.displayToastMessage(myContext, e.toString());
        }
    }
    
    /////////////// CLICK LISTENERS /////////////////
    /* Add Listener */
    private OnClickListener editItemListener = new OnClickListener(){
		public void onClick(View v){						
			// fetch the name of the user				
			try{
        		Intent intent = new Intent(myContext, GroceryGroupsEditActivity.class);
				intent.putExtras(getIntent().getExtras());
				TabGroupActivity parentActivity = (TabGroupActivity)getParent();
				parentActivity.startChildActivity("GroceryGroupsEditActivity", intent);
			}
			catch(Exception e){
				MyTools.displayToastMessage(myContext,e.toString());	
			}
		}
	};
    
	@Override
    public synchronized void onResume() {
        super.onResume();
       DBcursor.requery();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
     
        mDb.close();
    }
}
